package com.landmark;

import java.io.File;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class LandauCat extends SwingWorker<Boolean, Boolean> {

    FileWriter fw = null;
    FileWriter errorFile = null;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, String> htModelLinks = new Hashtable<String, String>();
    String status = "";
    JTextArea txtArea;

    @Override
    protected Boolean doInBackground() throws Exception {
        start();
        return true;
    }

    @Override
    protected void done() {
        Util.taskCompleteMsg(status);
    }

    public void start() {
        try {
            String dirName = "./outputs";

            Util.createDirectory(dirName);

            txtArea = Util.createOutputFile("Landau");
            HelperBean helperBean = Util.getHelperBean();

            fw = new FileWriter(helperBean.getOutputFile());
            errorFile = new FileWriter(helperBean.getErrorFile());

            // Here we get all the search pages from page that is already downloaded which contains all the model/product links
            String str = "D:\\Landau pages\\landau1.htm";
            processCategoryPage(str);

            txtArea.append("\nFiles are located at : \n" + helperBean.getOutputFile().getAbsolutePath() + "\n" + helperBean.getErrorFile().getAbsolutePath() + "\n");
            txtArea.append("Total products : " + htModelLinks.size() + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());

            Enumeration<String> keys = htModelLinks.keys();

            iterateCollection(htModelLinks);

            if (fw != null) {
                fw.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        status = "Done processing.";
        if (Util.getHelperBean().isTerminateCurrentProcess()) {
            status = "Process Terminated";
        }
        txtArea.append("\n" + status);
    }

    /**
     *
     * @param htLinks
     */
    private void iterateCollection(Hashtable<String, String> htLinks) throws Exception {
        Enumeration<String> keys = htLinks.keys();
        while (keys.hasMoreElements()) {
            if (Util.getHelperBean().isTerminateCurrentProcess()) {
                break;
            }
            String key = (String) keys.nextElement();
            txtArea.append("Processing page: " + key + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());
            sb = new StringBuffer();
            processModels(htLinks.get(key).toString());
            fw.write(sb.toString().replaceAll("\n", "").replaceAll("\r", "").replaceAll("    ", ""));
            fw.write("\n");
            fw.flush();
        }
    }

    /**
     *
     * @param aUrl
     */
    private void processModels(String aUrl) throws Exception {
        try {
            Parser parser = Util.getParserFromUrl(aUrl, null);
            // to know which URL/model we have the data for in the final output/file
            fw.write(aUrl+"\n");

            NodeList nl = parser.parse(null);

            NodeList tableNodes = nl.extractAllNodesThatMatch(new HasAttributeFilter("id", "description"), true);

            Node targetTableNode = tableNodes.elementAt(0);// retrives the table content where the description starts which we are intersetd in.			

            iterateTag(targetTableNode);

        } catch (Exception e) {
            try {
                errorFile.write(aUrl + " \n" + e.getMessage() + " \n");
                errorFile.flush();
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
    }

    /**
     *
     * @param aNodeList
     */
    private void iterateTag(Node aNodeList) {
        if (aNodeList instanceof TextNode) {
            TextNode text = (TextNode) aNodeList;
            sb.append(text.getText());
        } else if (aNodeList instanceof TagNode) {
            TagNode tag = (TagNode) aNodeList;
            NodeList nl = tag.getChildren();
            if (null != nl) {
                try {
                    for (NodeIterator i = nl.elements(); i.hasMoreNodes();) {
                        iterateTag(i.nextNode());
                    }
                } catch (Exception e) {
                    try {
                        errorFile.append(e.getMessage());
                    } catch (Exception e1) {
                    }
                }
            }
        }
    }

    private void processCategoryPage(String aUrl) throws Exception {
        Document doc = Jsoup.parse(new File(aUrl), null);
        Elements elements = doc.select("div.photo-holder").select("a[href]");
        for (Element element : elements) {
            String absoluteUrl = element.attr("abs:href");
            htModelLinks.put(absoluteUrl, absoluteUrl);
        }
    }
}